package com.loren.demo03.springboot;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class NettyServerConfig {

    private final NettyProperties nettyProperties;

    private final NettyServerHandler nettyServerHandler;

    @Bean(name = "bossGroup")
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup();
    }

    @Bean(name = "workerGroup")
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup();
    }

    @Bean(name = "serverBootstrap")
    public ServerBootstrap bootstrap() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(this.nettyServerHandler);
        return bootstrap;
    }

    @PostConstruct
    public void start() throws InterruptedException {
        bootstrap().bind(this.nettyProperties.getPort()).sync();
        log.info("Netty server start success, port = {}", this.nettyProperties.getPort());
    }

    @PreDestroy
    public void stop() {
        bossGroup().shutdownGracefully();
        workerGroup().shutdownGracefully();
        log.info("Netty server stop success.");
    }
}